/*
ajax 请求函数模块
返回值：promise 对象（异步返回的是 response.data）
*/
import axios from "axios";
import qs from "qs"; //使用qs将axios发送的数据格式转换为form-data格式
axios.defaults.withCredentials = true; //跨域避免session瞬间清除登陆信息

import axioStore from "./axioStore";

//进行路由拦截，路由切换时取消上个路由发出的请求
axios.interceptors.request.use(config => {
  config.cancelToken = new axios.CancelToken(function(cancel) {
    axioStore.commit("pushToken", { cancelToken: cancel });
  });
  return config;
});

// var cancelAxiosList = [];
// export { cancelAxiosList };
export default function ajax(url, data = {}, type = "GET") {
  // let axiosInstance = axios.create({
  //   // baseURL: process.env.API_ROOT_ATM,
  //   // cancelToken : new axios.CancelToken(function executor(cancel) {
  //   cancelToken: new axios.CancelToken(cancel => {
  //     cancelAxiosList.push({
  //       cancel
  //     });
  //   }),
  //   headers: {
  //     "Content-Type": "application/x-www-form-urlencoded"
  //   }
  // });

  return new Promise(function(resolve, reject) {
    // 执行异步 ajax 请求
    let promise;
    if (type === "GET") {

      // 拼接 url
      let dataStr = "";
      Object.keys(data).forEach(key => {
        dataStr += key + "=" + data[key] + "&";
      });
      if (dataStr !== "") {
        dataStr = dataStr.substring(0, dataStr.lastIndexOf("&"));
        url = url + "?" + dataStr;
      }

      promise = axios.get(url);
    } else {
      var data_afetr = qs.stringify(data);
      console.log('post---url:',url);
      console.log('post---data:',data);
      promise = axios.post(url, data_afetr);
    }

    promise
      .then(function(response) {
        // 成功了调用 resolve()
        resolve(response.data);
      })
      .catch(function(error) {
        // 失败了调用 reject()
        reject(error);
      });
  });
}
